# -*- coding: utf-8 -*-
import gitee_package
import log_package
import ini_package
from playwright_package import os_package
from gitee_package import re
from playwright_package import time_package
import playwright_package
import excel_package


# 获取gitee数据
def get_gitee_data():
    global ini_opt, goal_url, teacher_names
    try:
        # 连接gitee获取基本数据
        gitee_opt = gitee_package.Gitee_Option('https://gitee.com/zl_b/file_config.git',
                                               "06fbfe091fc755b51084d86966a14cc6")
        main_repo_data = gitee_opt.list_all_files_and_folders('金牛区相关信息')
        # 获取ini数据
        url = main_repo_data.get("重要配置.ini")
        if url:
            da = gitee_opt.get_gitee_repo_file(url)
            if da:
                ini_opt.read_ini_string(da)
                log_opt.write_success(f'成功获取gitee数据，【重要配置.ini】信息成功！')
                goal_url = ini_opt.get_section_option('通知课时和交补链接', 'url')
                if goal_url:
                    for i in ini_opt.list_section_options('金牛区支教老师'):
                        if ini_opt.get_section_option('金牛区支教老师', i) == 'True':
                            teacher_names.append(i)
                    return True
                else:
                    raise Exception('获取【goal_url】信息失败！')
            else:
                raise Exception('获取【重要配置.ini】信息失败！')
        else:
            raise Exception('未找到-【重要配置.ini】！')


    except Exception as e:
        log_opt.write_error(f'获取gitee出现错误{e}')
        return False


# 处理数据
def make_data():
    try:
        course_file_name = '课时统计'
        traffic_file_name = '成都金牛地区交通备用金核销明细表'
        course_file_name_path = f'file/{course_file_name}.xlsx'
        traffic_file_name_path = f'file/{traffic_file_name}.xlsx'
        main_file_name = '金牛区支教老师课时和交补统计'
        main_file_name_path = f'file/{main_file_name}.xlsx'

        ex_course = excel_package.Excel_Option(course_file_name_path)
        ex_course.open_file()
        ex_traffic = excel_package.Excel_Option(traffic_file_name_path)
        ex_traffic.open_file()

        ex_course_data = ex_course.get_sheet_all_data('统计信息')
        ex_traffic_data = ex_traffic.get_sheet_all_data('教师小计汇总')

        ex_main = excel_package.Excel_Option(main_file_name_path)
        ex_main.create_new_excel()
        ex_main.delete_sheet('Sheet')
        ex_main.create_new_sheet('统计信息')
        ex_main.write_headers_to_sheet('统计信息', ['序号', '教师姓名', '课时', '交通补贴', '助教', '备注'])

        a = 1
        for t in teacher_names:
            y = 1
            d = dict()
            d['序号'] = a
            d['教师姓名'] = t
            for k, v in ex_course_data.items():
                if v['教师姓名'] == t:
                    d['课时'] = v['课时数']
                    break
            for k, v in ex_traffic_data.items():
                if v['姓名'] == t:
                    d['交通补贴'] = v['补贴金额']
                    break

            if not d.get('课时'):
                d['课时'] = 0
            if not d.get('交通补贴'):
                d['交通补贴'] = 0

            # 插入数据
            ex_main.insert_row_values('统计信息', a + 1, d)
            a += 1

        ex_main.modify_region_alignment('统计信息', horizontal='center', vertical='center')
        ex_main.save_file()
        ex_main.close_file()
        ex_course.close_file()
        ex_traffic.close_file()
        return True

    except Exception as e:
        log_opt.write_error(f'处理数据出现错误{e}')
        return False


# 录入链接
def fill_in_data():
    try:
        main_file_name = '金牛区支教老师课时和交补统计'
        main_file_name_path = f'file/{main_file_name}.xlsx'
        ex_main = excel_package.Excel_Option(main_file_name_path)
        ex_main.open_file()
        all_data = ex_main.get_sheet_all_data('统计信息')
        # print(all_data)
        web_opt = playwright_package.Playwright_Management()
        log_opt.write_info('正在等待钉钉登陆...')
        if web_opt.dingding_login():
            log_opt.write_success('钉钉登陆成功！')
            for row_data in all_data.values():
                try:
                    web_opt.page.goto(goal_url)
                    # web_opt.page.pause()
                    # print(row_data)
                    log_opt.write_info(f'正在录入【{row_data["教师姓名"]}】的课时和交补数据...')
                    # 选择人员
                    web_opt.page.get_by_text("请选择成员").click()
                    web_opt.page.wait_for_timeout(timeout=3000)
                    web_opt.page.get_by_placeholder("搜索人员").click()
                    web_opt.page.get_by_placeholder("搜索人员").fill(str(row_data['教师姓名']))
                    web_opt.page.get_by_text(str(row_data['教师姓名'])).first.click()

                    # page.pause()
                    # time.sleep(30)

                    # 填写课时
                    p = row_data['课时']
                    if not row_data['课时']:
                        p = 0
                    web_opt.page.get_by_placeholder("请输入数字").first.fill(str(p))
                    # 填写交补
                    p = row_data['交通补贴']
                    if not row_data['交通补贴']:
                        p = 0
                    web_opt.page.get_by_placeholder("请输入数字").nth(1).fill(str(p))
                    # 填写助教次数
                    p = row_data['助教']
                    if not row_data['助教']:
                        p = 0
                    web_opt.page.get_by_placeholder("请输入数字").nth(2).fill(str(p))
                    # 核算月份
                    p = time_opt.current_month() - 1
                    web_opt.page.get_by_placeholder("请输入数字").nth(3).fill(str(p))
                    # 选择发送时间
                    web_opt.page.get_by_placeholder("请选择日期").click()
                    web_opt.page.get_by_role("button", name="现在").click()
                    web_opt.page.get_by_role("button", name="确定").click()
                    web_opt.page.locator("label").nth(3).click()

                    # 填写备注
                    p = row_data['备注']
                    if not row_data['助教']:
                        p = ""
                    web_opt.page.get_by_placeholder("请输入内容").fill(str(row_data['备注']))
                    # 提交表单
                    web_opt.page.get_by_role("button", name="提交表单").click()
                    log_opt.write_success(f'录入【{row_data["教师姓名"]}】的课时和交补数据成功！')
                    web_opt.page.wait_for_timeout(timeout=1000)
                except Exception as e:
                    log_opt.write_error(f'录入【{row_data["教师姓名"]}】的课时和交补数据失败！')
                    continue
                # web_opt.page.pause()
            return True
        else:
            raise Exception('钉钉登陆失败！')

    except Exception as e:
        log_opt.write_error(f'录入链接数据出现错误{e}')
        return False


if __name__ == '__main__':
    print(
        '''请选择模式\n[0]:仅生成课时和交补记录\n[1]:生成课时和交补记录并录入链接\n[2]:直接录入链接\n为空或者其他值默认为0''')
    user_select_mode = input('请输入您要选择的模式：\n')
    try:
        user_select_mode = int(user_select_mode)
    except Exception as e:
        user_select_mode = 0

    # 初始化
    time_opt = time_package.Time_Option()
    time_opt.start_timing()
    log_opt = log_package.Logging_Option()
    log_opt.write_info('正在初始化...')
    ini_opt = ini_package.Config_Option()
    os_opt = os_package.Os_Option()
    os_opt.make_file_folder('file')
    os_opt.make_file_folder('log')
    goal_url = None
    teacher_names = list()
    log_opt.write_success('初始化成功！')

    try:
        log_opt.write_info('正在获取gitee数据...')
        if get_gitee_data():
            log_opt.write_success('获取gitee数据成功！')
            if user_select_mode == 1:
                if make_data():
                    log_opt.write_success('生成数据成功！')
                    if fill_in_data():
                        log_opt.write_success('录入数据成功！')
                    else:
                        raise Exception('录入数据异常！')
                else:
                    raise Exception('生成数据异常！')
            elif user_select_mode == 2:
                if fill_in_data():
                    log_opt.write_success('录入数据成功！')
                else:
                    raise Exception('录入数据异常！')
            else:
                if make_data():
                    log_opt.write_success('生成数据成功！')
                else:
                    raise Exception('生成数据异常！')
        else:
            raise Exception('获取gitee数据失败!')
    except Exception as e:
        log_opt.write_error(f'程序异常：{e}')
    finally:
        log_opt.write_success('程序运行完毕！')
        log_opt.write_info(f'程序用时：{time_opt.end_timing()}')
        time_opt.timesleep(3)
